package com.zhao.pay;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jdom.JDOMException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.zhao.base.TokenThread;
import com.zhao.util.HttpRequest;
import com.zhao.util.XMLUtil;

import net.sf.json.JSONObject;

/**
 * Servlet implementation class PayServlet
 */
@WebServlet("/PayServlet")
public class PayServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static Logger log=LoggerFactory.getLogger(PayServlet.class);
   
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/plain;charset=UTF-8"); 
		String resultjson="0";
		PrintWriter o=response.getWriter();
		SortedMap<Object, Object> params=new TreeMap<Object,Object>();
		params.put("appid", TokenThread.appid);
		params.put("mch_id", TokenThread.mch_id);
		params.put("nonce_str",MysteriousUtil.getNoncestr());
		params.put("body", "信通测试");
		Date date=new Date();
		DateFormat format=new SimpleDateFormat("yyyyMMddHHmmss");
		String time=format.format(date);
		String uuid=UUID.randomUUID().toString().replaceAll("-","").substring(16, 26);
		String out_trade_no="TS"+time+uuid;
		String openId="";
		Cookie[] cookie = request.getCookies();
		for (int i = 0; i < cookie.length; i++) {
		Cookie cook = cookie[i];
		if(cook.getName().equalsIgnoreCase("OpenID")){ //获取键 
			openId=cook.getValue().toString();    //获取值 
		}
		}
		if(openId.equals(""))
		{
			resultjson+="无法获取用户信息，请重新登录操作！";
			o.print(resultjson);
			o.close();
			o=null;
			return;
		}
		params.put("out_trade_no", out_trade_no);
		params.put("total_fee", "1");
		params.put("spbill_create_ip", request.getRemoteAddr());
		params.put("notify_url", "http://test.epms.cn/jgt/wx/PaySuess");
		params.put("trade_type", "JSAPI");
		params.put("openid", openId);
        params.put("sign", MysteriousUtil.createSign("UTF-8", params));
		String requestXML=MysteriousUtil.getRequestXml(params);
		log.debug("requestXML================="+requestXML);
		//访问微信统一支付接口，返回xml格式字符串
		String result=HttpRequest.httpsPayRequest("https://api.mch.weixin.qq.com/pay/unifiedorder", "POST", requestXML);
		log.debug("result================="+result);
	    //解析为细腻返回信息
		Map<String,String> map=null;
	    try {
			map=XMLUtil.doXMLParse(result);
		} catch (JDOMException e) {
			// TODO Auto-generated catch block
			log.debug("0访问支付接口失败！");
			e.printStackTrace();
		}
	   
	    if(map!=null)
	    {
	    	SortedMap<Object, Object> pars=new TreeMap<Object,Object>();
	    	pars.put("appId", TokenThread.appid);
	    	pars.put("timeStamp", Long.toString(new Date().getTime()));
	    	pars.put("nonceStr",MysteriousUtil.getNoncestr());
	    	pars.put("package", "prepay_id="+map.get("prepay_id"));
			pars.put("signType", "MD5");
			pars.put("paySign", MysteriousUtil.createSign("UTF-8", pars));
	    	pars.put("packageValue", "prepay_id="+map.get("prepay_id"));
	    	pars.put("sendUrl", "http://test.epms.cn/jgt/pages/wx/PersonalCircle/pay_tk_demo.jsp?tid="+out_trade_no);
	    	String userAgent=request.getHeader("user-agent");
	    	char agent=userAgent.charAt(userAgent.indexOf("MicroMessenger")+15);
	    	pars.put("agent", new String(new char[]{agent}));
	    	resultjson=JSONObject.fromObject(pars).toString();
	    	log.debug(resultjson);
	    	o.print(resultjson);
			o.close();
			o=null;
	    }
	    else
	    {
			o.print(resultjson);
			o.close();
			o=null;
	    }
	}
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
